<template>
  <div class="S-how">
    <div class="cen">
      <h2>这是监测数据展示界面</h2>
      检测到的温度：{{recvData.temp}} ℃
      <br>
      检测到的光照强度：{{recvData.light}} Gx
      <br>
      检测到的土壤湿度：{{recvData.moisture}} %
      <br>
      当前模式：{{mode}}

    </div>
  </div>
</template>

<script>
  import mqtt from 'mqtt' // 引入mqtt模块

  export default {
    name: 'S-how',
    data() {
      return {
        client: null,
        mode: '',
        options: {
          connectTimeout: 4000, // 超时时间
          clientId: 'k0w64ZsZg4R.device11|securemode=2,signmethod=hmacsha256,timestamp=1714996971133|', // id
          username: 'device11&k0w64ZsZg4R', // 用户名
          password: 'e51f71aa87191f9d2e0ba30fba1745f74dd1424ca205dfa6f64fb1c04367776c', // 密码
          cleanSession: false,
          keepAlive: 60 // 心跳值，心跳值太大可能会连接不成功，这个参考文档
        },
        subscription: {
          topic: '/k0w64ZsZg4R/device11/user/get',
          qos: 0
        },
        publication: {
          topic: '/k0w64ZsZg4R/device11/user/update',
          qos: 0,
          payload: {}
        },
        recvData: {} // 接收的消息
      }
    },
    updated() {
      this.recvData = JSON.parse(this.recvData)
      if (this.recvData.mode == 0) {
        this.mode = '自动'
      } else {
        this.mode = '手动'
      }
    },
    methods: {
      dada(msg) {
        console.log(msg)
        this.publication.payload = JSON.stringify(msg)
        console.log(this.publication.payload)
        const { topic, qos, payload } = this.publication
        this.client.publish(topic, payload, qos, error => {
          if (error) {
            console.log('发布失败', error)
          } else {
            console.log('发布成功')
          }
        })
      },
      doConnected() {
        console.log('正在连接...')
        try {
          this.client = mqtt.connect('ws://iot-06z00c2el7pe360.mqtt.iothub.aliyuncs.com:443', this.options)
        } catch (error) {
          console.log('mqtt连接失败: ', error)
        }
        this.client.on('connect', () => {
          console.log('连接成功')
          this.doSubscribe() // 订阅主题
        })
        // 接收消息处理
        this.client.on('message', (topic, message) => {
          console.log('收到来自', topic, '的消息', message.toString())
          this.recvData = message.toString()
        })
        // 连接错误处理
        this.client.on('error', (error) => {
          console.log('连接出错: ', error)
        })
        // 重新连接处理
        this.client.on('reconnect', () => {
          console.log('重新连接...')
        })
      },
      doDisconnected() {
        try {
          this.doUnSubscribe()
          this.client.end()
          console.log('断开连接')
        } catch (error) {
          console.log('断开连接失败: ', error.toString())
        }
      },
      doSubscribe() {
        const { topic, qos } = this.subscription
        this.client.subscribe(topic, qos, (error, res) => {
          if (!error) {
            console.log('订阅成功')
            console.log(res)
            this.recvData = res
            console.log(this.recvData)
          } else {
            console.log('订阅失败')
          }
        })
      },
      doUnSubscribe() {
        const { topic } = this.subscription
        this.client.unsubscribe(topic, error => {
          if (error) {
            console.log('取消订阅失败', error)
          }
        })
      },
      doPublish() {
        const { topic, qos, payload } = this.publication
        this.client.publish(topic, payload, qos, error => {
          if (error) {
            console.log('发布失败', error)
          } else {
            console.log('发布成功')
          }
        })
      }
    },
    created() {
      this.doConnected()
      this.doSubscribe()
    },
    mounted() {
      this.$bus.$on('event', this.dada)
    }
  }
</script>
<!-- mounted() {
      setInterval(() => {
        axios.get('http://localhost:8080/server1/user1').then(
          (response) => {
            // console.log('返回的数据', response.data)
            this.data = response.data[0]
          },
          (error) => {
            console.log('数据请求失败', error.message)
          }
        )
      }, 3000)
    } -->



<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  h2 {
    margin: 0;
    padding: 0;
  }

  .cen {
    width: 500px;
    height: 300px;
    background-color: #ffffff85;
    margin: 100px auto;
    text-align: center;
    line-height: 60px;
    font-size: 20px;
  }
</style>